package com.ray.magicBlock;

import com.ray.magicBlock.exception.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author bo shen
 * @Description: 模块下发组件
 * @Class: BlockDispatch
 * @Package com.ray.magicBlock
 * @date 2019/10/10 14:49
 * @company <p>杭州传化陆鲸科技有限公司</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Component
@Slf4j
public class BlockDispatch<P,O,R>  implements ApplicationContextAware{
    private ApplicationContext applicationContext;
    /**
     * 下发器
     * @param group
     * @param strategy
     * @return
     */
    public R dispatch(String group,String strategy,P params,O object) {
        //获取策略对象
        String beanName = Utils.getBeanName(group,strategy);
        if(!StringUtils.hasLength(beanName)){
            throw new BlockException(BlockException.Code_500,"beanName is null");
        }
        Strategy<P,O,R> strategyBean = applicationContext.getBean(beanName,Strategy.class);
        if(StringUtils.isEmpty(strategyBean)){
            throw new BlockException(BlockException.Code_500,"strategyBean is null");
        }
        return  strategyBean.execute(params,object);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
       this.applicationContext = applicationContext;
    }
}
